package com.anysoft.visitdd.example;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.logging.Logger;

public class VisiterClient {
    static final String USER_PUB_KEY = "2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0d4d4947664d413047435371475349623344514542415155414134474e4144434269514b42675144327a474d59774a69714b2b467a74763452514331676e31544b0d426d4d37585376756b443570446f44304d2b50704f363461546c2f6361764e526e4e6e58347975464e396231626a77634a435259744546776474656e765954670d2b6b65496268746e5a78586b6e73444d73576d694e7166397a6e6a5768362f6e657746452f6168633565526578702f585446583857654f444e762f4a787038510d4b6d67382b46665163695452674c745168774944415141420d2d2d2d2d2d454e44205055424c4943204b45592d2d2d2d2d0d";

    // 查询一页数据
    static void queryRecords(String pubKey) throws Exception {
        var gson = new Gson();
        var rsaEnc = new RsaEncrypter(ProjectSecurityCommon.ALG_RSA_FOR_ANDROID, pubKey);
        var j = new JsonObject();
        var fields = new JsonArray();
        fields.add("Qhdm");
        fields.add("Qhmc");
        j.add("fields", fields);
        j.addProperty("pageIndex", 1);
        j.addProperty("pageSize", 100);
        var msg = gson.toJson(j);
        System.out.println("msg");
        System.out.println(msg);
        var msgEncd = rsaEnc.encrypt(msg);
        try (var hc = HttpClient.newBuilder().build()) {
            var req = App.fillToken(USER_PUB_KEY).uri(URI.create(App.API_HEAD + "/gateway/page/Xzqh"))
                    .method("GET", HttpRequest.BodyPublishers.ofString(msgEncd)).build();
            var res = hc.send(req, HttpResponse.BodyHandlers.ofString());
            var resBody = res.body();
            var parser = new JsonParser();
            var arm = parser.parse(resBody).getAsJsonObject();
            Logger.getGlobal().info(arm.toString());
        }
    }

    static void getRecord(String pubKey, JsonObject postData) throws Exception {
        var gson = new Gson();
        var rsaEnc = new RsaEncrypter(ProjectSecurityCommon.ALG_RSA_FOR_ANDROID, pubKey);
        var msg = gson.toJson(postData);
        Logger.getGlobal().info(msg);
        var msgEncd = rsaEnc.encrypt(msg);
        try (var hc = HttpClient.newBuilder().build()) {
            var req = HttpRequest.newBuilder().uri(URI.create(App.API_HEAD + "/gateway/single/Honghuahui"))
                    .method("GET", HttpRequest.BodyPublishers.ofString(msgEncd)).build();
            var res = hc.send(req, HttpResponse.BodyHandlers.ofString());
            var resBody = res.body();
            var parser = new JsonParser();
            var arm = parser.parse(resBody).getAsJsonObject();
            Logger.getGlobal().info(arm.toString());
        }
    }
}
